/**
 * Created by Forcs on 16/4/12.
 */

var mongoose = require('mongoose');
var events = require('events');
var util = require('util');
var co = require('co');
var Utils = require('../utils/Utils');

var DbService = function (options) {
  var _self = this;
  _self._options = options || {};
  _self._db = undefined;
  _self._models = [];
  events.EventEmitter.call(_self);
};

util.inherits(DbService, events.EventEmitter);

DbService.prototype.ready = function (callback) {
  var _self = this;
  var db = mongoose.connection;
  db.on('connected', function () {
    _self.emit('connected', arguments);
  });
  db.on('disconnected', function () {
    _self.emit('disconnected', arguments);
  });
  db.on('reconnected', function () {
    _self.emit('reconnected', arguments);
  });
  db.on('error', function () {
    _self.emit('error', arguments);
  });
  db.once('open', function () {
    _self._db = db;
    _self.emit('open', db);
    co(function * () {
      var models = _self._models;
      if (models && models.length) {
        var i = models.length;
        while (i--) {
          var ready = models[i].$manager.start();
          if (Utils.isPromise(ready)) {
            yield ready;
          }
        }
      }
      if (callback) {
        callback.call(_self, db);
      }
    }).catch(function (err) {
      if (callback) {
        callback.call(_self, db, err);
      }
    });
  });
  mongoose.connect('mongodb://' + _self._options.host + ':' + _self._options.port + '/' + _self._options.name);
};

DbService.prototype.db = function () {
  return this._db;
};

DbService.prototype.registerModels = function (modelsConfig) {
  if (modelsConfig.require) {
    for (var key in modelsConfig.require) {
      this._models.push(modelsConfig.require[key]);
    }
  }
  if (modelsConfig.rel && modelsConfig.require) {
    for (var key in modelsConfig.rel) {
      if (modelsConfig.require[key]) {
        var rels = modelsConfig.rel[key];
        rels.forEach(function (item) {
          modelsConfig.require[key].$manager.register(item.$manager);
        })
      }
    }
  }
};

module.exports = DbService;